<?php

namespace App\Http\Controllers;

use App\Models\TempEmail;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest')->only('toLogin');
    }

    public function toLogin()
    {
        return view('auth.login');
    }


    public function login(Request $request)
    {
        $data = $this->validate($request, [
            "email" => ['required', 'email'],
            "password" => ['required', 'min:6', 'max:8']
        ]);

        if (\Auth::attempt($data)) {
            if (\Auth::user()->is_active) {
                session()->flash('success','登录成功,欢迎您回来');
                return redirect()->route('users.show',["user"=>\Auth::user()]);
            } else {
                session()->flash('danger','该用户没有激活');
                return redirect()->back();
            }
        } else {
            session()->flash('danger','登录失败,账号和密码不匹配');
            return redirect()->back()->withInput();
        }

    }


    public function active(Request $request)
    {
        $tempEmail = TempEmail::where('user_id', $request->user_id)->firstOrFail();

        if ($tempEmail->code == $request['code']) {
            User::where('id',$tempEmail->user_id)->update([
                'is_active' => 1
            ]);
            session()->flash('success','激活成功');
        }

        return redirect()->route('login');
    }

    public function logout()
    {
        \Auth::logout();
        session()->flash('success','退出成功!');
        return redirect()->route('login');
    }
}
